# -*- coding: utf-8 -*-

from . import odoo_fields as fields
import json

import logging

_logger = logging.getLogger(__name__)


class BaseModel(object):
    @classmethod
    def value_get(cls, record):
        one = {}
        for fld, val in record.items():
            if hasattr(cls, fld):
                meta = getattr(cls, fld)
                one[meta.field_name] = meta.value_get(val)
        return one


class NcOrderLine(BaseModel):
    # 读取 NC 订单, 写入 odoo 前. 转换为 odoo 需要的格式
    # 对应 fp.sale.order.line

    rownumber = fields.Integer('明细行号', 'sequence')  # 关键字段, 以此查询明细行
    saleinvoicebid = fields.Char('商品类别编码', 'line_pk')
    saleordernumber = fields.Char('订单号', 'order_num')
    loadingnumber = fields.Char('配载号', 'logistics_num')
    ph = fields.Char('批次号', 'product_lot')

    swfl_code = fields.Char('商品类别编码', 'vat_product_code')
    swfl_name = fields.Char('商品类别名称', 'vat_product_name')
    itemcode = fields.Char('商品名称', 'product_code')
    itemname = fields.Char('商品名称', 'product_name')
    itemspec = fields.Char('规格', 'product_spec')
    unit = fields.Char('单位', 'product_uom')

    taxrate = fields.Integer('税率', 'tax_ratio')

    price = fields.Float('单价', 'price_unit')
    quantity = fields.Float('数量', 'quantity')
    memo = fields.Text('备注', 'note')

    @classmethod
    def value_get(cls, record):
        one = super().value_get(record)

        one['name'] = one['product_name']
        return one


class NcOrder(BaseModel):
    # 读取 NC 订单, 写入 odoo 前. 转换为 odoo 需要的格式
    # 对应 fp.sale.order

    saleinvoiceid = fields.Char('发票ID', 'name')
    saleinvoicenumber = fields.Char('发票号', 'invoice_num')

    saleinvoicetype = fields.Selection(selection=[
        (1, 'sale'),  # 销售
        (2, 'refund'),  # 退货
        (3, 'plus_neg'),  # 正负行
        (4, 'discount'),  # 折扣
    ], string="类型", field_name='biz_type')

    orgcode = fields.Char('公司代码', 'company_code')
    orgname = fields.Char('公司名称', 'company_name')

    invoice_issuer_tel = fields.Char('用户电话', 'user_phone')

    customercode = fields.Char('客户代码', 'partner_code')
    customername = fields.Char('客户名称', 'partner_name')

    totalmoney = fields.Float('含税金额', 'amount_total')
    memo = fields.Text('备注', 'note')

    status = fields.Selection(selection=[
        ('confirm', 'confirm'),  # 确认
        ('cancel', 'cancel'),  # 取消
    ], string="状态", field_name='api_status')

    lines = fields.One2many(NcOrderLine, '明细行', 'line_ids')

    @classmethod
    def after_read(cls, record):
        return cls.value_get(record)


class OdooNc(object):
    def after_read(self, vals_list):
        records = []
        for vals in vals_list:
            one = NcOrder.after_read(vals)
            one['api_jsondata'] = json.dumps(vals)
            records.append(one)

        return records
